
import request  from "@/utils/request";
import { defineStore } from "pinia";
//Ts类型导入
import { ApiRes ,CategoryItem , TopCategory , SubCategory} from "@/types/data"
//常量数据
import { topCategory } from '../constants'
const DefaultCategory = topCategory.map(item => {
  return {
    name:item
  }
})

const store = defineStore('category',{
    state(){
        return {
            //一级导航不常改变，可以设置常量，优化
            list: DefaultCategory as CategoryItem[],
            topCategory: {} as TopCategory,
            subCategory: {} as SubCategory,
        }
    },
    actions:{
        //头部导航渲染请求
        async reqGetCategoryList(){
            const res = await request.get<ApiRes<CategoryItem[]>>('/home/category/head')
            // console.log(res);

            res.data.result.forEach(item => {
                item.open=false   //自己添加的数据，用于二级导航的显示隐藏
            })
            this.list = res.data.result
            // console.log(this.list);
        },
        //show hide 方法控制 二级导航显示和隐藏 
        show(id:string){
            const category =this.list.find(item =>item.id===id)
            category!.open = true
        },
        hide(id: string) {
            const category = this.list.find((item) => item.id === id)
            category!.open = false
        },
        //面包屑导航渲染
        async  getTopCategory(id: string) {
            const res = await request.get<ApiRes<TopCategory>>('/category', {
                params: {
                    id,
                },
                })
            this.topCategory = res.data.result
        },
        //
        async getSubFilter(id: string) {
            const res = await request.get<ApiRes<SubCategory>>(
              '/category/sub/filter',
              {
                params: {
                  id,
                },
              }
            )
            this.subCategory = res.data.result
          },
    },
})

export default store